//
//  HLHomeRefreshControl.swift
//  weibo-snh
//
//  Created by 黄力 on 15/12/23.
//  Copyright © 2015年 HLTest. All rights reserved.
//

import UIKit
import SnapKit

enum HLHomeRefreshControlStatus: Int {
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}

//自定义高度
private var RefreshControlHeight: CGFloat = 60

class HLHomeRefreshControl: UIControl {
    
    //记录当前状态的属性
    private var newStatus: HLHomeRefreshControlStatus = .Normal
    
    //状态属性
    var status: HLHomeRefreshControlStatus = .Normal {
        didSet {
            switch status {
            case .Normal:
                //更改文字
                refreshTitleView.text = "下拉起飞"
                //图片动画
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.refreshIconView.transform = CGAffineTransformIdentity
                    //当从刷新状态变换成默认状态时才修改
                    if self.newStatus == .Refreshing {
                        //获取当前显示范围
                        var inset = self.superScrollView!.contentInset
                        //修改
                        inset.top -= RefreshControlHeight
                        self.superScrollView?.contentInset = inset
                    }
                })
                //记录状态
                newStatus = status
            case .Pulling:
                //更改文字
                refreshTitleView.text = "准备起飞"
                //图片动画
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.refreshIconView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                //显示指示器
                refreshIndicatorView.hidden = false
                //隐藏图片
                refreshIconView.hidden = true
                //开始转动
                refreshIndicatorView.startAnimating()
                sendActionsForControlEvents(.ValueChanged)
                //让父视图完全显示自定义控件
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    //获取当前显示范围
                    var inset = self.superScrollView!.contentInset
                    //修改
                    inset.top += RefreshControlHeight
                    self.superScrollView?.contentInset = inset
                })
                //记录状态
                newStatus = status
            }
        }
    }
    
    override init(frame: CGRect) {
        //设置frame
        let rect = CGRectMake(0, -RefreshControlHeight, MainScreenWidth, RefreshControlHeight)
        super.init(frame: rect)
        backgroundColor = UIColor.orangeColor()
        //设置界面
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置界面
    private func setupUI() {
        //添加子视图
        addSubview(refreshIconView)
        addSubview(refreshTitleView)
        addSubview(refreshIndicatorView)
        //设置约束
        //图片
        refreshIconView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-40)
        }
        //文字
        refreshTitleView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(refreshIconView)
            make.left.equalTo(refreshIconView.snp_right)
        }
        //指示
        refreshIndicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(refreshIconView)
        }
        //默认隐藏指示视图
        refreshIndicatorView.hidden = true
    }
    
    //结束刷新
    func endRefreshing() {
        let t = dispatch_time(DISPATCH_TIME_NOW, Int64(1) * Int64(NSEC_PER_SEC))
        //延迟
        dispatch_after(t, dispatch_get_main_queue()) { () -> Void in
            self.status = .Normal
            //隐藏指示器
            self.refreshIndicatorView.hidden = true
            //显示图片
            self.refreshIconView.hidden = false
            //结束转动
            self.refreshIndicatorView.stopAnimating()
        }
        
    }
    
    //获取父控件
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //获取父控件
        superScrollView = newSuperview as? UIScrollView
        //注册监听
        superScrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
    }
    
    //监听的属性改变时调用该方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //判断父控件存在时
        guard let superSV = superScrollView else {
            return
        }
        //获取当前scollView的现实范围
        let inset = superSV.contentInset
        //计算最大拖动Y值
        let scrollMaxY = inset.top + RefreshControlHeight
        //获取Y偏移量
        let offsetY = -(superSV.contentOffset.y)
        //根据偏移量来更改状态
        //判断是否在拖拽状态下
        if superSV.dragging {
            if status == .Normal && offsetY > scrollMaxY {
                status = .Pulling
            }else if status == .Pulling && offsetY < scrollMaxY {
                status = .Normal
            }
        }else {
            //没有再拖拽状态下,而且当前时准备起飞的状态,就进行刷新
            if status == .Pulling {
                status = .Refreshing
            }
        }
        
    }
    
    //控件销毁时移除监听
    deinit {
        superScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //保存父控件的属性
    private var superScrollView: UIScrollView?
    
    //MARK: 懒加载子控件
    //图片
    private lazy var refreshIconView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //文字
    private lazy var refreshTitleView: UILabel = UILabel(title: "下拉起飞", titleColor: UIColor.lightGrayColor(), titleFont: 14)
    //指示视图
    private lazy var refreshIndicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)

}
